﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class SysManage_UserInfo : UserPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Login_Psd_A.Text = DefaultPass;
            OrganDLL_Bind(Organ_A);
            OrganDLL_Bind(Organ_R);
            SetPager();
            Role_Bind();
        }
    }

    private void OrganDLL_Bind(DropDownList argDll)
    {
        string sqlStr = @"SELECT t1.space_organ,t2.rgt,t1.organ
                                  FROM (SELECT CONCAT(U_Repeat('　',(COUNT(t2.organ)-1)),t1.organ) AS space_organ,t1.organ
                                  FROM u_organ_t t1,u_organ_t t2
                                 WHERE t1.lft BETWEEN t2.lft AND t2.rgt
                                 GROUP BY t1.organ) t1
                                  LEFT JOIN u_organ_t t2
                                    ON t1.organ = t2.organ
                                 WHERE t2.if_valid = 'Y'
                                 ORDER BY t2.lft";
        argDll.DataSource = OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, null);
        argDll.DataTextField = "space_organ";
        argDll.DataValueField = "organ";
        argDll.DataBind();
        argDll.Items.Insert(0, new ListItem("请选择…", ""));
        argDll.SelectedIndex = 0;
    }

    private void Role_Bind()
    {
        string sqlstr = "SELECT data_code,data_name FROM u_pub_data_t WHERE data_type='role_list' AND if_valid = 'Y' ORDER BY order_num";
        RoleList.DataSource = OracleHelper.ExecuteDataSet(sqlstr, CommandType.Text, null);
        RoleList.DataTextField = "data_name";
        RoleList.DataValueField = "data_code";
        RoleList.DataBind();
    }

    private void SetPager()
    {
        PagedDataSource pds = new PagedDataSource();
        DataSet ds = GetUser();
        UserPager.RecordCount = ds.Tables[0].Rows.Count;
        pds.DataSource = ds.Tables[0].DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = UserPager.PageSize;
        pds.CurrentPageIndex = UserPager.CurrentPageIndex - 1;
        UserList.DataSource = pds;
        UserList.DataBind();
    }

    protected void UserList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Charge")
        {
            if (IsOnlyAdmin(e.CommandArgument.ToString()))
            {
                JQueryAlert("唯一已启用系统管理员请勿禁用！");
            }
            else
            {
                ModifyStatus(e.CommandArgument.ToString());
            }
            SetPager();
        }
        else if (e.CommandName == "Reset")
        {
            ChangePassword(e.CommandArgument.ToString());
            JQueryAlert("密码重置成功！");
        }
        else if (e.CommandName == "ModifyUser")
        {
            RoleSet_Bind(e.CommandArgument.ToString());
            Login_Name_R.Text = e.CommandArgument.ToString();
            DataTable dt = GetUser(e.CommandArgument.ToString());
            Real_Name_R.Text = dt.Rows[0]["real_name"].ToString();
            if (dt.Rows[0]["organ"].ToString().Length > 0)
            {
                Organ_R.SelectedValue = dt.Rows[0]["organ"].ToString();
            }
            else
            {
                Organ_R.SelectedIndex = 0;
            }
            Page.ClientScript.RegisterStartupScript(this.GetType(), "open"
                , "$(function() {$('#ModifyUserDiv').dialog('open');})", true);
        }
    }

    private void RoleSet_Bind(string arg)
    {
        string sqlstr = @"SELECT data_code FROM u_pub_data_t WHERE data_type='role_list' AND if_valid = 'Y'  
                                AND data_code IN(SELECT role_code FROM u_user_role_t 
                                                            WHERE login_name =:login_name AND if_valid='Y')";
        OracleParameter[] _params = {
                    new OracleParameter(":login_name",OracleType.VarChar,16)
            };
        _params[0].Value = arg;
        DataSet ds = OracleHelper.ExecuteDataSet(sqlstr, CommandType.Text, _params);
        IList<string> s = new List<string>();
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            s.Add(dr["data_code"].ToString());
        }
        foreach (ListItem c in RoleList.Items)
        {
            c.Selected = s.Contains(c.Value);
        }
    }

    private bool IsOnlyAdmin(string arg)
    {
        int count = -1;
        string sqlStr = @"SELECT COUNT(1) FROM u_user_info_t t1 
                                  WHERE if_valid = 'Y'
                                      AND login_name <> :login_name
                                      AND EXISTS(SELECT 1 FROM u_user_role_t t2
                                                        WHERE t2.if_valid = 'Y' 
                                                            AND t2.role_code = '" + RoleSys + "' AND t1.login_name = t2.login_name)";
        OracleParameter[] _params = {
                    new OracleParameter(":login_name",OracleType.VarChar,16)
            };
        _params[0].Value = arg;
        count = Int32.Parse(OracleHelper.ExecuteScalar(sqlStr, CommandType.Text, _params).ToString());
        return (count == 0);
    }

    private int ModifyStatus(string user_login)
    {
        string sqlStr = "UPDATE u_user_info_t SET if_valid=DECODE(if_valid,'Y','N','Y') WHERE login_name =:login_name";
        OracleParameter[] _params = {
                new OracleParameter(":login_name",OracleType.VarChar,16)
            };
        _params[0].Value = user_login;
        return OracleHelper.ExecuteNonQuery(sqlStr, CommandType.Text, _params);
    }

    private int ChangePassword(string arg)
    {
        int effRow = 0;
        string sqlStr = "UPDATE u_user_info_t SET login_psd =:login_psd WHERE login_name =:login_name";
        OracleParameter[] _params = {
                new OracleParameter(":login_psd",OracleType.VarChar,200),
                new OracleParameter(":login_name",OracleType.VarChar,16)
            };
        _params[0].Value = Tools.EncryptPasswordByMD5(DefaultPass);
        _params[1].Value = arg;
        effRow = OracleHelper.ExecuteNonQuery(sqlStr, CommandType.Text, _params);
        return effRow;
    }

    protected void BtnCreate_Click(object sender, EventArgs e)
    {
        if (ULoginOnly())
        {
            AddUser();
            User_Login_A.Text = "";
            Real_Name_A.Text = "";
            Organ_A.SelectedIndex = 0;
            SetPager();
            JQueryAlert("用户已新增成功!");
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "fail"
                , "$(function() {$('#AddUserDiv').dialog('open');alert('登录名已存在，请重新输入。');})", true);
        }
    }

    private bool ULoginOnly()
    {
        string sqlstr = "SELECT COUNT(1) FROM u_user_info_t WHERE login_name = :login_name";
        OracleParameter[] _params = {
                new OracleParameter(":login_name",OracleType.VarChar,16)
            };
        _params[0].Value = User_Login_A.Text.Trim();
        return OracleHelper.ExecuteScalar(sqlstr, CommandType.Text, _params).ToString().Equals("0");
    }

    private int AddUser()
    {
        string sqlStr = "insert into u_user_info_t (login_name,login_psd,real_name,organ,if_valid)"
                        + " values(:login_name,:login_psd,:real_name,:organ,:if_valid)";

        OracleParameter[] _param = {
			new OracleParameter(":login_name",OracleType.VarChar,16),
			new OracleParameter(":login_psd",OracleType.VarChar,200),
            new OracleParameter(":real_name",OracleType.NVarChar,12),
            new OracleParameter(":organ",OracleType.NVarChar,20),
			new OracleParameter(":if_valid",OracleType.VarChar,2)
			};

        _param[0].Value = User_Login_A.Text.Trim();
        _param[1].Value = Tools.EncryptPasswordByMD5(DefaultPass);
        _param[2].Value = Real_Name_A.Text.Trim();
        _param[3].Value = Organ_A.SelectedValue;
        _param[4].Value = "Y";

        return OracleHelper.ExecuteNonQuery(sqlStr, CommandType.Text, _param);
    }

    private DataSet GetUser()
    {
        string sqlStr = "SELECT login_name,real_name,if_valid,join_date,organ FROM u_user_info_t";
        if (Login_Name_I.Text.Trim().Length > 0)
        {
            sqlStr = sqlStr + " WHERE login_name like '%" + Tools.ReplaceString(Login_Name_I.Text.Trim(), 16) + "%' ";
        }
        sqlStr = sqlStr + " ORDER BY join_date DESC";
        return OracleHelper.ExecuteDataSet(sqlStr, CommandType.Text, null);
    }

    protected void QueryUser_Click(object sender, EventArgs e)
    {
        SetPager();
    }

    protected void UserPager_PageChanged(object sender, EventArgs e)
    {
        SetPager();
    }

    protected void ModifyBtn_Click(object sender, EventArgs e)
    {
        if (IsOnlyAdmin(Login_Name_R.Text) && !RoleList.Items.FindByValue(RoleSys).Selected)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "sysinfo"
                , "$(function() {$('#ModifyUserDiv').dialog('open');alert('唯一系统管理员请勿取消系统管理员角色！');})", true);
            return;
        }
        string sqlstr = "U_MODIFY_USERINFO_P";
        OracleParameter[] _param = {
			new OracleParameter("V_ROLE",OracleType.VarChar,1024),
            new OracleParameter("V_REAL",OracleType.NVarChar,20),
            new OracleParameter("V_ORGAN",OracleType.NVarChar,20),
			new OracleParameter("V_LOGIN",OracleType.VarChar,16),
            new OracleParameter("V_OPERATOR",OracleType.VarChar,16)			
	    };
        _param[0].Value = GetRoleString();
        _param[1].Value = Real_Name_R.Text.Trim();
        _param[2].Value = Organ_R.SelectedValue;
        _param[3].Value = Login_Name_R.Text;
        _param[4].Value = Session["LoginUser"].ToString();
        int r = OracleHelper.ExecuteNonQuery(sqlstr, CommandType.StoredProcedure, _param);
        if (r > 0)
        {
            SetPager();
            JQueryAlert("用户信息更新成功！");
        }
    }

    private string GetRoleString()
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i <= RoleList.Items.Count - 1; i++)
        {
            if (RoleList.Items[i].Selected)
            {
                sb.Append("|");
                sb.Append(RoleList.Items[i].Value);
            }
        }
        if (sb.Length > 0)
            sb.Remove(0, 1);
        return sb.ToString();
    }
}
